//
//  KASecurityVC.swift
//  kano
//
//  Created by Sophia on 2024/8/21.
//

import UIKit
import PopupDialog

class KASecurityVC: KABaseVC {
    
    static let var_itemCellId = "KASecurityCell"
    lazy var var_tableView: UITableView = {
        let var_tableView = UITableView()
        var_tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        var_tableView.backgroundColor = .colorf2f2f5
        var_tableView.frame = CGRect(x: 0.0, y: UIDevice.ka_fullNavHeight, width: view.width, height: UIDevice.ka_viewHeight)
        var_tableView.register(KASecurityCell.self, forCellReuseIdentifier: Self.var_itemCellId)
        var_tableView.dataSource = self
        var_tableView.delegate = self
        var_tableView.separatorStyle = .none
        var_tableView.tableHeaderView = var_headerView
        return var_tableView
    }()
    lazy var var_dataArray = [KARowInfo]()
    
    lazy var var_headerView = {
        let var_headerView = UIView()
        var_headerView.backgroundColor = .colorf2f2f5
        var_headerView.frame = CGRectMake(0, 0, var_screenWidth, kscale(12))
        return var_headerView
    }()
    
    lazy var var_loginOutBtn: UIButton = {
        let var_loginOutBtn = UIButton(frame: CGRectMake(kscale(66), var_closeBtn.y-kscale(56), view.width-kscale(132), kscale(50.0)))
        var_loginOutBtn.setTitle("Log out", for: .normal)
        var_loginOutBtn.setTitleColor(.themeColor, for: .normal)
        var_loginOutBtn.titleLabel?.font = UIFont.systemFont(ofSize: kscale(17), weight: .bold)
        var_loginOutBtn.backgroundColor = .colorBDBDF5
        var_loginOutBtn.layer.cornerRadius = kscale(25)
        var_loginOutBtn.layer.masksToBounds = true
        var_loginOutBtn.addTarget(self, action: #selector(ka_loginOutBtnClick), for: .touchUpInside)
        return var_loginOutBtn
    }()
    
    lazy var var_closeBtn: UIButton = {
        let var_closeBtn = UIButton(frame: CGRectMake(kscale(66), var_screenHeight-UIDevice.ka_safeBottom-kscale(82), view.width-kscale(132), kscale(50.0)))
        var_closeBtn.setTitle("Cancel account", for: .normal)
        var_closeBtn.setTitleColor(.colorFF4141, for: .normal)
        var_closeBtn.titleLabel?.font = UIFont.systemFont(ofSize: kscale(17), weight: .bold)
        var_closeBtn.backgroundColor = .clear
        var_closeBtn.layer.cornerRadius = kscale(25)
        var_closeBtn.layer.masksToBounds = true
        var_closeBtn.addTarget(self, action: #selector(ka_closeBtnClick), for: .touchUpInside)
        return var_closeBtn
    }()
    
    @objc func ka_loginOutBtnClick() {
        let alert = KAAlertView.alert(withTitle: "Are you sure you want to log out?", subtitle: "") { _ in 
            
        }
        alert.addAction(KAAlertAction(title: "Cancel", titleColor: .black, backgroundColor: .clear))
        alert.addAction(KAAlertAction(title: "Confirm", titleColor: .blue, backgroundColor: .clear) { action in
            KAUserManager.shared.userLogout()
        })
        alert.show()
    }
    @objc func ka_closeBtnClick() {
        let alertVC = KAAlertVC(title: "Are you sure you want to close this account?", subTitle: "Current account:\(KAUserManager.shared.user.mobile.maskedNumber)", actionTitle: "Cancellation", image: "alert_warn")
        let popup = PopupDialog(viewController: alertVC, buttonAlignment: .horizontal, transitionStyle: .zoomIn, tapGestureDismissal: true, panGestureDismissal: false)
        alertVC.handler = {
            popup.dismiss()
            self.navigationController?.pushViewController(KACloseAccVC(), animated: true)
        }
        let containerAppearance = PopupDialogContainerView.appearance()
        containerAppearance.cornerRadius = 20
        self.present(popup, animated: true, completion: nil)
    }
}

extension KASecurityVC {
    override func viewDidLoad() {
        super.viewDidLoad()
        ka_configData()
        ka_setUI()
    }
    func ka_configData() {
        let changePhone = KARowInfo(title: "Change your sign-in mobile phone", isFirst: true, isLast: false, type: .changePhone)
        let changeLoginPwd = KARowInfo(title: "Change Login Password", isFirst: false, isLast: false, type: .changeLoginPwd)
        
        var changeTransPwd = KARowInfo(title: "Change transaction password", isFirst: false, isLast: false, type: .changeTransPwd)
        
        //let mailbox = KARowInfo(title: "Bind mailbox", isFirst: false, isLast: true, type: .bindmailbox)

        var cancelAcc = KARowInfo(title: "Cancel account", isFirst: false, isLast: true, type: .cancelAcc)
        
        if let json = KADBDBManager.ka_getObject(by: "homeInfo") as? String {
            let homeInfo = json.kj.model(KAHomeInfo.self)
            if homeInfo!.hasSetPassword {
                cancelAcc.isFirst = false
                cancelAcc.isLast = true
                var_dataArray.append(changePhone)
                var_dataArray.append(changeLoginPwd)
                var_dataArray.append(changeTransPwd)
                var_dataArray.append(cancelAcc)
            } else {
                var_dataArray.append(changePhone)
                var_dataArray.append(changeLoginPwd)
                var_dataArray.append(cancelAcc)
            }
        } else {
            var_dataArray.append(changePhone)
            var_dataArray.append(changeLoginPwd)
            var_dataArray.append(cancelAcc)
        }
        
        
    }
    func ka_setUI() {
        view.backgroundColor = .colorf2f2f5
        view.addSubview(var_tableView)
//        view.addSubview(var_closeBtn)
        view.addSubview(var_loginOutBtn)
        ka_showCustomerNavBar(type: .normal)
        var_navBar.var_titleLabel.text = "Account security"
    }
}

extension KASecurityVC: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        var_dataArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let var_cell: KASecurityCell = KASecurityCell.ka_cell(for: tableView)
        let rowData = var_dataArray[indexPath.row]
        var_cell.var_titleLabel.text = rowData.title
        
        if (rowData.isFirst && rowData.isLast) {
            var_cell.var_cornerView.ka_addCorner(withRadius: kscale(10))
        } else {
            if (rowData.isFirst) {
                var_cell.var_cornerView.ka_addTopCorner(withRadius: kscale(10))
            }
            if (rowData.isLast) {
                var_cell.var_cornerView.ka_addBottomCorner(withRadius: kscale(10))
            }
        }
        return var_cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return kscale(50.0)
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let rowData = var_dataArray[indexPath.row]

        switch rowData.type {
        case .changePhone:
            navigationController?.pushViewController(KAChangeMobileVC(), animated: true)
        case .changeLoginPwd:
            navigationController?.pushViewController(KAChangePwdVC(), animated: true)
        case .changeTransPwd:
            KAFlutterManager.showFlutterVC(route: "/modifyTradePwd", parameter: ["mobile" : KAUserManager.shared.user.mobile])

        case .cancelAcc:
            ka_closeBtnClick()
            
        default: break
        }
    }
}
